package com.dotstone.chipism.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.EventBusEntity;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Scene;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.view.WheelView;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SceneSettingActivity extends BaseActivity{
    public static TextView tvTitle;
    private Button btnAdd;
    private View btnBack;
    private RelativeLayout scene_relative_rl;
    private RelativeLayout scene_create_rl;
    WheelView wheelview;
    private TextView mStatusBar;
    List<String> list=new ArrayList<>();
    LoopView loopView;
    private List<Scene> mScenes;
    private Toast toast;
    private TextView tip_tv;
    private String deviceid;
    private int position;
    private String sceneid;
    public static final int ADD_SUCCESS_RESULT_CODE = 0x02;
    public static final int ADD_SUCCESS_REQUEST_CODE = 0x01;
    private int bsid;
    private String scenename;

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.scene_relative_rl:
             /*   wheelview.setVisibility(View.VISIBLE);
                mScenes = DeviceManager.getInstance().getScenes();
              if(list.size()>0){
                  list.clear();
              }
                for (int i=0;i<mScenes.size();i++){
                    list.add(mScenes.get(i).getSceneName());
                }
                wheelview.setOffset(1);
                wheelview.setSeletion(list.size()/2);
                wheelview.setItems(list);
                wheelview.invalidate();
                wheelview.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                    @Override
                    public void onSelected(int selectedIndex, String item) {
                        Log.d(TAG, "selectedIndex: " + selectedIndex + ", item: " + item);
                    }
                });*/

                mScenes = DeviceManager.getInstance().getScenes();
                if(mScenes.size()>0){
                    tip_tv.setVisibility(View.GONE);
                    loopView.setVisibility(View.VISIBLE);
                    btnAdd.setVisibility(View.VISIBLE);
                    if(list.size()>0){
                        list.clear();
                    }
                    for (int i=0;i<mScenes.size();i++){
                        list.add(mScenes.get(i).getSceneName());
                    }
                    loopView.setNotLoop();
                    //设置原始数据
                    loopView.setItems(list);
                    loopView.setCenterTextColor(Color.parseColor("#9cd1d7"));

                    //设置初始位置
                    loopView.setInitPosition(list.size()/2);
                    loopView.setCurrentPosition(list.size()/2);
                    sceneid= mScenes.get(list.size()/2).getSceneId();//默认选中情景id
                    //滚动监听
                    loopView.setListener(new OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(int index) {
                            if (toast == null) {
                                toast = Toast.makeText(SceneSettingActivity.this, "item " + index, Toast.LENGTH_SHORT);
                            }
                            toast.setText(list.get(index));
                           sceneid= mScenes.get(index).getSceneId();
                           scenename= mScenes.get(index).getSceneName();
                            //toast.show();
                        }
                    });
                }else{
                    tip_tv.setVisibility(View.VISIBLE);
                    loopView.setVisibility(View.GONE);
                    btnAdd.setVisibility(View.GONE);
                }

                break;
            case R.id.scene_create_rl:
                Intent intent = new Intent(SceneSettingActivity.this, SceneEditActivity.class);
                intent.putExtra("position", -1);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intent);
                break;
            case R.id.nextstep:
                if(bsid==-1){//添加
                try {
                JSONObject obj = new JSONObject();
                obj.put("key", "10000");
                obj.put("position", position);
                obj.put("requestTime", "" + System.currentTimeMillis());
                obj.put("deviceId", deviceid);
                obj.put("sceneId",sceneid);
                obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                    OkHttpUtils.postString().url(HttpURL.SCENE_ADD)
                            .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                            .content(obj.toString())
                            .build().readTimeOut(5000)
                            .writeTimeOut(5000).connTimeOut(5000)
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    showToast("添加失败");
                                    // mSVProgressHUD.dismiss();
                                }

                                @Override
                                public void onResponse(String response) {
                                    // mSVProgressHUD.dismiss();
                                    Log.i("onResponse" , "onResponse:" + response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String value = jsonObject.getString("resultCode");
                                        if (value.equals("1")){
                                            showToast("添加成功");
                                            EventBus.getDefault().post(
                                                    new EventBusEntity("success","success"));
                                           // setResult(ADD_SUCCESS_RESULT_CODE);
                                            finish();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                }else{//修改
                    try {
                    JSONObject obj1 = new JSONObject();
                    obj1.put("key", "10000");
                    obj1.put("position", position);
                    obj1.put("requestTime", "" + System.currentTimeMillis());
                    obj1.put("id", bsid);
                    obj1.put("deviceId", deviceid);
                    obj1.put("sceneId",sceneid);
                    obj1.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
                    OkHttpUtils.postString().url(HttpURL.SCENE_UPDATE)
                            .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                            .content(obj1.toString())
                            .build().readTimeOut(5000)
                            .writeTimeOut(5000).connTimeOut(5000)
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {
                                    showToast("修改失败");
                                    // mSVProgressHUD.dismiss();
                                }

                                @Override
                                public void onResponse(String response) {
                                    // mSVProgressHUD.dismiss();
                                    Log.i("onResponse" , "onResponse:" + response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String value = jsonObject.getString("resultCode");
                                        if (value.equals("1")){
                                            showToast("修改成功");
                                            EventBus.getDefault().post(
                                                    new EventBusEntity("success","success"));
                                           // setResult(ADD_SUCCESS_RESULT_CODE);
                                            finish();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                } catch (JSONException e) {
                e.printStackTrace();
            }
                }
                break;
            case R.id.back_layout:
                finish();
                break;
        }

    }



    @Override
    public void initParms(Bundle parms) {

    }

    @Override
    public View bindView() {
        return null;
    }
    public int bindLayout() {
        return R.layout.activity_scene_setting;
    }

    @Override
    public void initView(View view) {
        btnBack = $(R.id.back_layout);
        tvTitle = $(R.id.title_tv);
        btnAdd = $(R.id.nextstep);
        mStatusBar = $(R.id.tv_statusBar_mian);
        tip_tv = $(R.id.tip_tv);
        deviceid=getIntent().getStringExtra("deviceid");
        sceneid=getIntent().getStringExtra("sceneid");
        position = getIntent().getIntExtra("position",50);
        bsid = getIntent().getIntExtra("bsid",-1);
        scene_relative_rl = $(R.id.scene_relative_rl);
        scene_create_rl = $(R.id.scene_create_rl);
        loopView = $(R.id.loopView);
      //  wheelview =  $(R.id.main_wv);
     //   wheelview.setVisibility(View.GONE);

        boolVersion();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void setListener() {
        tvTitle.setText("情景设置");
        btnAdd.setText("确定");
        btnAdd.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        scene_relative_rl.setOnClickListener(this);
        scene_create_rl.setOnClickListener(this);
    }

    @Override
    public void doBusiness(Context mContext) {

    }

    public void boolVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            // getWindow().addFlags(
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // 改变titlebar的高度
            int statusbarHeight = BarUtils.getStatusBarHeight(this);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
            layoutParams1.height = statusbarHeight;
            mStatusBar.setLayoutParams(layoutParams1);
            mStatusBar.setVisibility(View.VISIBLE);
        } else {
            mStatusBar.setVisibility(View.GONE);
        }
    }
}
